<template>
    <div class="app-container">
      <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      v-show="showSearch"
      >
      <el-row :gutter="20">
        <!-- <el-col :span="6">
          <el-form-item label="" prop="serialCode">
          <el-input
            v-model="queryParams.serialCode"
            placeholder="预算申请表编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        </el-col> -->
        <el-col :span="6">
            <el-form-item label="" prop="budgetProjectCode">
                <el-input
                    v-model="queryParams.budgetProjectCode"
                    placeholder="预算项目编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    />
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item prop="category">
                <el-select
                    filterable
                    v-model="queryParams.category"
                    placeholder="类别（预算大类）"
                    clearable
                    size="small"
                    style="width:100%"
                    @keyup.enter.native="handleQuery"
                    @change="handleChange"
                >
                 <el-option
                    v-for="(item,index) in CategoryList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item prop="classify">
                <el-select
                  filterable
                    v-model="queryParams.classify"
                    placeholder="分类（预算子类）"
                    clearable
                    size="small"
                    style="width:100%"
                    @keyup.enter.native="handleQuery"
                >
                 <el-option
                    v-for="(item,index) in ClassifyList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-col>

        <el-col :span="6">
            <el-form-item label="" prop="budgetProjectName">
                <el-input
                    v-model="queryParams.budgetProjectName"
                    placeholder="预算项目名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    />
            </el-form-item>
        </el-col>
             <el-col :span="6">
            <el-form-item label="" prop="department">
              <el-select
                v-model="queryParams.department"
                placeholder="所属部门"
                clearable
                style="width:100%"
                size="small"
                @keyup.enter.native="handleQuery">
                <el-option
                  v-for="(item,index) in departmentList"
                  :key="index"
                  :label="item"
                  :value="item"/>
            </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="" prop="budget">
                <el-input
                    v-model="queryParams.budget"
                    placeholder="预算总金额"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    />
            </el-form-item>
        </el-col>
        </el-row>
        
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
      
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
        >新增基础数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload action="#" :auto-upload="false" :show-file-list="false"
           
            accept="application/msexcel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :on-change="upLoadExcel">
            <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="small"
        >导入基础数据</el-button>
        </el-upload>
            
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="small"
          @click="handleExport"
          :disabled='multiple'
        >导出基础数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="multipleTable" v-loading="loading" :data="formulationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column type="index" fixed width="55" label="序号" align="center" />
      <el-table-column label="预算项目编号" fixed  align="center" prop="budgetProjectCode"  width="180" />
      <el-table-column label="类别（预算大类）" align="center" width="230" prop="category" show-overflow-tooltip></el-table-column>
      <el-table-column label="分类（预算子类）" align="center" prop="classify" width="230" show-overflow-tooltip></el-table-column>
      <el-table-column label="预算项目名称"  align="center" prop="budgetProjectName" width="230" show-overflow-tooltip/>
      <el-table-column label="数据权限"  align="center" prop="dataPermission" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_data_permission" :value="scope.row.dataPermission"/>
        </template>
      </el-table-column>
      <el-table-column label="所属部门"  align="center" prop="department" width="180"></el-table-column>
      <el-table-column label="预算总金额" sortable align="center" prop="budget" width="180"></el-table-column>
      <el-table-column label="备注1" align="center"  prop="note" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column label="备注2" align="center"  prop="note1" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right"  >
        <template slot-scope="scope">
          <template>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handlelrocess(scope.row)"
          >修改</el-button>
          </template>
          <template >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-coordinate"
              @click="budgetDel(scope.row)"
            >删除</el-button>
          </template>
          <template >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="budgetDel(scope.row)"
            >申请预算确认</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
        <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" width="50%" append-to-body>  
            <el-form label-width="130px" ref="form" :model="form" :rules="formRules">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item  label="类别(预算大类)" prop="category">
                    <el-select style="width:100%" filterable allow-create  clearable v-model="form.category" placeholder="请选择类别(预算大类)">
                      <el-option
                        v-for="(item,index) in CategoryList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="分类(预算子类)" prop="classify">
                    <el-select style="width:100%"  filterable allow-create  clearable v-model="form.classify" placeholder="请选择分类(预算子类)">
                      <el-option
                        v-for="(item,index) in ClassifyList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="预算总金额" prop="budget">
                    <el-input clearable v-model="form.budget" placeholder="请输入预算总金额"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="budgetProjectName" label="预算项目名称">
                    <el-input clearable v-model="form.budgetProjectName" placeholder="请输入预算项目名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="dataPermission" label="数据权限">
                    <!-- <el-input clearable v-model="form.dataPermission" placeholder="数据权限"></el-input> -->
                    <el-select v-model="form.dataPermission" placeholder="数据权限" style="width:100%" clearable>
                      <el-option
                        v-for="dict in dict.type.sys_data_permission"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item  label="所属部门" prop="department">
                    <el-select style="width:100%" clearable v-model="form.department" placeholder="请选择部门">
                      <el-option
                        v-for="(item,index) in departmentList"
                        :key="index"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="note" label="备注1">
                    <el-input type="textarea" :rows="4" clearable  maxlength="200" show-word-limit v-model="form.note" placeholder="请输入备注1"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="note" label="备注2">
                    <el-input type="textarea" :rows="4" clearable  maxlength="200" show-word-limit v-model="form.note1" placeholder="请输入备注2"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button  @click="handleSave" type="primary" >保存</el-button>
              <el-button  @click="cancel">返回</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { exportExe } from "@/api/operations/IpAddress.js";
import {
  BudgetAdd,
  BudgetList,
  BudgetDel,
  BudgetEdit,
  budget_department,
  BudgetIntroduction,
  BudgetCategory,
  BudgetClassify,
  BudgetExport,
  getBudget
} from '../../../../api/financial/budgetExecution'
export default {
  name: 'budgetTodo',
  dicts:['sys_data_permission'],
  data() {
    // 正数、负数、小数且不限制小数位
    const reg = /^-?\d+(\.\d+)?$/
    const totalAmountNum = (rules, value, callback) => {
      if (!value) {
          callback(new Error('请输入预算总金额'))
      }
      if (!reg.test(value)) {
        // console.log(typeof value,'777');
        callback(new Error('包含非数字字符'));
      } else {
          callback()
        }
      }
      return {
        // 非多个禁用
      multiple: true,
          // 选中数组
          ids: [],
          // 显示搜索条件
          showSearch: true,
          // 弹窗标题
          title: null,
          // 遮罩层
          loading: false,
          dataVisible: false,
          importVisible: false,
        exportVisible: false,
          // 是否显示预算执行的弹出层
          dialogVisible:false,
          //总条数
          total: 0,
            form: {
                classify: null,
                category: null,
                budget: null,
                budgetProjectName: null,
                department: null,
              note: null,
                dataPermission:null,
            },
          queryParams: {
              pageNum: 1,
              pageSize: 10,
              budgetProjectCode: null,
              budgetProjectName: null,
              category: null,
              department: null,
              classify: null,
              budget:null,
            },
            formRules: {
              classify: { required: true, message: '分类不能为空', trigger: 'blur' },
              category: { required: true, message: '类别不能为空', trigger: 'blur' },
              budget: [
                { required: true, message: '预算总金额不能为空', trigger: 'blur' },
                { validator: totalAmountNum, trigger: 'blur' },
                { max: 50, message: '预算总金额最大50个字符', trigger: 'blur' }
              ],
              budgetProjectName: [{ required: true, message: '预算项目名称不能为空', trigger: 'blur' },
              { max: 50, message: '预算项目名称最大50个字符', trigger: 'blur' }
              ],
              department: { required: true, message: '部门不能为空', trigger: 'blur' },
              dataPermission: { required: true, message: '数据权限不能为空', trigger: 'blur' },
              // TotalAmount: [{ required: true, message: '总金额不能为空', trigger: 'blur' },
              // ],
            },
            deltOptions: [],
            sourcesList: [],
            departmentList: [],
            formulationList: [],
            CategoryList: [],
            ClassifyList:[]
        }
    },
  created() {
      this.getList()
    },
  mounted() {
      this.getList()
    },
  methods: {
       // 文件状态改变时的钩子
       async upLoadExcel(file) {
            // 文件上传前做一下判断
            // const type_ALLOWD = ['doc', 'docx', 'txt', 'xls', 'xlsx', 'text', 'pdf']
            const type_ALLOWD = ['xls', 'xlsx']
            const fileType = file.raw.name.substring(
                file.raw.name.lastIndexOf('.') + 1
            )
            // 判断文件格式
            if (type_ALLOWD.indexOf(fileType) === -1) {
                this.$message({
                  
                    message: "只能上传以'.xls'、 '.xlsx'结尾的文件,请重新上传！",
                    type: 'error',
                    
                });
            } else {
                let formData = new FormData()
                formData.append('file', file.raw)
               
                const res = await BudgetIntroduction (formData)
               
                if (res) {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                    } else {
                        this.$message.warning(res.msg)
                    }
                    this.getList()
                } else {
                    this.$message.error('导入失败')
                } 
              
            }
        },
        // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
        beforeUploadFile(file) {
            console.log('before upload');
            console.log(file);
            let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
            let size = file.size / 1024 / 1024;
            if (extension !== 'xlsx') {
                this.$message.warning('只能上传后缀是.xlsx的文件');
            }
            if (size > 10) {
                this.$message.warning('文件大小不得超过10M');
            }
        },
      handleChange(val) {

      },
      // 部门下拉
      inItPage() {
        budget_department().then(res => {
          for(let i = 0;i<res.data.length;i++){
            this.departmentList.push(res.data[i].dictLabel)
          }
        })
      },
      // 上一步
      previousStep() {
        this.dataVisible = false
        this.importVisible = true
      },
      // 下一步
      nextStep() {
        // 上传文件解析渲染
      },
      // 返回按钮
      cancel() {
        this.dialogVisible = false
        this.reset()
      },
      // 修改
      handlelrocess(row) {
        this.reset()
        const id = row.id || this.ids;
        getBudget(id).then(response => {
          this.form = response
          this.dialogVisible = true
          this.title = '修改预算生成'
        })
        
      },
      handleNext() {
        this.importVisible = false
        this.dataVisible = true
      },
      // 删除操作
      budgetDel(row) {
        // BudgetDel({id: row.id}).then(res => {
        //   console.log(res,"rrrr");
        // })
        const ids = row.id || this.ids;
        const titles = row.title || this.titles;
      this.$modal
        .confirm('是否确认删除文件标题为"' + ids + '"的数据项？')
        .then(function() {
          return BudgetDel(ids);
        })
        .then(() => {
          // this.getList();
          this.getList()
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          classify: null,
          category: null,
          budget: null,
          budgetProjectName: null,
          department: null,
        };
        this.resetFormData("form");
      },
      /** 重置按钮操作 */
        resetQuery() {
          this.resetFormData("queryForm");
          this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
        // 新增基础数据按钮
      handleAdd() {
        this.reset()
        this.category()
        this.classify()
          this.title = '新增预算生成'
          this.dialogVisible = true
        },
        //新增预算生成
      handleSave() {
          this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            BudgetEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false
              this.getList()
            });
          } else {
            BudgetAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false
              this.getList()
            });
          }
        }
      });
          // BudgetAdd(this.form).then(res => {
          //   console.log(res,"res>>>>");
          //   this.dialogVisible = false
          //   this.handleQuery()
          // })
        },
        category() {
          BudgetCategory().then(res => {
            const {data} = res
            this.CategoryList = data
          })
        },
      classify() {
        BudgetClassify().then(res => {
            const {data} = res
            this.ClassifyList = data
          })
        },
        //预算执行列表
      getList() {
          this.loading = true
          BudgetList(this.queryParams).then(res => {
            this.formulationList = res.rows
            this.total = res.total
            this.loading = false;
          })
          this.category()
          this.classify()
          this.inItPage()
        },
        //导入基础数据
        handleImport() {
          this.importVisible = true

        },
        // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.budgetProjectCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      let list = [];
      if(this.ids.length > 0){
        this.ids.forEach(ele => {
         let  obj = this.formulationList.find(item => item.budgetProjectCode==ele);
          list.push(obj)
        });
        console.log(list,"88888888888888");
        BudgetExport(list).then(res=>{
          if(res){
          const blob = new Blob([res],{type: 'application/vnd.ms-excel'});
          const fileName ="预算生成申请表.xlsx";
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
            this.$refs.multipleTable.clearSelection();
          }

       })

      }
    }
    }
}

</script>

<style lang="less" scoped>

</style>
